package com.cswnode.Controller;

import com.cswnode.Annotations.LoginJudgment;
import com.cswnode.Entity.Message;
import com.cswnode.Entity.Page;
import com.cswnode.Entity.User;
import com.cswnode.Service.MessageService;
import com.cswnode.Service.UserService;
import com.cswnode.Util.CommunityUtil;
import com.cswnode.Util.Constant;
import com.cswnode.Util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @author csw
 * @create 2020/9/26 13:52
 */
@Controller
public class MessageController {
    @Autowired
    private MessageService messageService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private UserService userService;
    @LoginJudgment
    @GetMapping("/message/list")
    public String toLetterPage(Model model, Page page){
        User user = hostHolder.getUser();
        page.setLimit(5);
        page.setPath("/message/list");
        page.setRows(messageService.findConversationcount(user.getId()));
        //查询所有的消息列表
        List<Message> conversations = messageService.findConversations(user.getId(), page.getOffset(), page.getLimit());
        List<Map<String,Object>> MessageVoList = new ArrayList<>();
        if (conversations != null){
            for (Message message : conversations){
                Map<String,Object> map = new HashMap<>();
                //插入最新的聊天的信息
                map.put("message",message);
                //未读的信息数量
                map.put("unreadMessageCount",messageService.findsUnreadMessage(user.getId(),message.getConversationId()));
                //私聊的信息数量
                map.put("privateMessageCount",messageService.findPrivateMessageCount(message.getConversationId()));
                //回复的对象
                //如果当前的用户Id等于from_id，则私聊的对象id为to_id
                // 如果当前的用户Id等于to_id，则私聊的对象id为from_id
                int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
                map.put("target",userService.findUserById(targetId));
                MessageVoList.add(map);
            }
        }
        model.addAttribute("messages",MessageVoList);
        //该账户所有的未读信息数量
        int LetterUnreadCount = messageService.findsUnreadMessage(user.getId(),null);
        model.addAttribute("LetterUnreadCount",LetterUnreadCount);
        return "site/letter";
    }

    /**
     * 获得状态码为0的私信id
     * @param messages
     * @return
     */
    private List<Integer> getIds(List<Message> messages){
        List<Integer> ids = new ArrayList<>();
        if (messages != null){
            for (Message message : messages) {
                if (hostHolder.getUser().getId() == message.getToId() && message.getStatus() == 0){
                  ids.add(message.getId());
                }
            }
        }
        return ids;
    }
    @LoginJudgment
    @GetMapping("/message/detail/{conversationId}")
    public String toMessageDetail(@PathVariable("conversationId") String conversationId,Model model,Page page){
        User user = hostHolder.getUser();
        page.setLimit(5);
        page.setRows(messageService.findPrivateMessageCount(conversationId));
        page.setPath("/message/detail/"+conversationId);
        List<Message> privateMessageList = messageService.findPrivateMessageList(conversationId, page.getOffset(), page.getLimit());
        List<Map<String,Object>> letters = new ArrayList<>();
        for (Message message : privateMessageList) {
            Map<String,Object> map = new HashMap<>();
            map.put("message",message);
            map.put("formUser",userService.findUserById(message.getFromId()));
            letters.add(map);
        }
        model.addAttribute("letters",letters);
        List<Integer> ids = getIds(privateMessageList);
        if (!ids.isEmpty()){
            messageService.updateMessageStatus(ids,Constant.HAVE_READ);
        }

        //私聊的目标
        model.addAttribute("target",getFromUser(conversationId));
        return "site/letter-detail";
    }


    private User getFromUser(String conversationId){
        User user = hostHolder.getUser();
        String [] ID = conversationId.split("_");
        Integer ID1 = Integer.parseInt(ID[0]);
        Integer ID2 = Integer.parseInt(ID[1]);
        if (user.getId() == ID1){
            return userService.findUserById(ID2);
        }else {
            return userService.findUserById(ID1);
        }
    }

    //发送私信
    @LoginJudgment
    @ResponseBody
    @PostMapping("/message/add")
    public String addMessage(String toName,String content){
        User target = userService.findUserByName(toName);
        if (target == null){
            return CommunityUtil.getJsonString(1,"目标用户不存在");
        }
        Message message = new Message();
        message.setContent(content);
        message.setFromId(hostHolder.getUser().getId());
        message.setToId(target.getId());
        message.setCreateTime(new Date());
        if (message.getToId() < message.getFromId()){
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }else {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        }
        int rows = messageService.insertMessage(message);
        if (rows == 0){
            return CommunityUtil.getJsonString(1,"发送私信失败");
        }
        return CommunityUtil.getJsonString(0,"发送成功！");
    }
}
